package cn.com.shopec.erp.core.base.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import cn.com.shopec.erp.common.utils.DateEditor;


/**    
 * @Title:	BaseController.java 
 * @Package:	com.broadengate.common.web.controller 
 * @Description:	Controller基类
 * @version V1.0 
 */
public class BaseController {
	
	public BaseController(){
		
	}
	
	
	private String COUNTER_CONDITION = "不合要求";
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new DateEditor());
		binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, false));
	}

	/**
	 * 格式化服务端验证数据格式
	 * @param bindingResult	验证结果
	 * @return
	 */
	public String formatBindingResultMessage(BindingResult bindingResult){
			List<FieldError> errList = bindingResult.getFieldErrors();
			StringBuffer messageBuffer = new StringBuffer();
			for (FieldError fieldError : errList) {
				messageBuffer.append("<li>{'").append(fieldError.getRejectedValue()).append("' ("+fieldError.getField()+")] '"+COUNTER_CONDITION);
				String defaultMessage = fieldError.getDefaultMessage();
				if(defaultMessage != null && !"".equals(defaultMessage)){
					messageBuffer.append(defaultMessage);
				}
				messageBuffer.append("'};</li>");
			}
			return messageBuffer.toString();
	}
	
	/**
	 * 绑定验证信息
	 * @param view
	 * @param result
	 */
	public void BinderValidaDate(ModelAndView view ,BindingResult ... results){
		for (BindingResult result : results) {
			List<FieldError> errList = result.getFieldErrors();
			view.getModel().put("validatorErrorList", errList);
		}
	}
	
	/**
	 * 绑定验证信息
	 * @param view
	 * @param result
	 */
	public void BinderValidaDate(ModelAndView view ,String ... results){
			
			@SuppressWarnings("unchecked")
			List<FieldError> errList = (List<FieldError>) view.getModel().get("validatorErrorList");
			if(errList == null){
			    errList = new ArrayList<FieldError>();
			}
			
			
			for (String result : results) {
				FieldError error = new FieldError("", "", result);
				errList.add(error);
			}
			
			view.getModel().put("validatorErrorList", errList);
	}

}
